import { NzMessageService, UploadFile } from 'ng-zorro-antd';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { LoginService } from '../../../service/login.service';
import { ServiceResult, Constant } from '@core/constant';
import { SettingsService, TitleService } from '@delon/theme';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import { ReuseTabService } from '@delon/abc';
import { UserService, User } from 'app/service/user/user.service';
import {Router} from "@angular/router";

@Component({
    selector: 'extra-setting',
    styleUrls: ['./setting.component.less'],
    templateUrl: './setting.component.html'
})
export class SettingComponent implements OnInit {

    active = 1;
    profileForm: FormGroup;
    pwd = {
        old_password: '',
        new_password: '',
        confirm_new_password: ''
    };
    avatarUrl: string;
    loading = false; // 上传用
    uploadUrl = '';
    avatarParam = { type: 'Avatar', userId: ''};


    constructor(
        fb: FormBuilder,
        private router: Router,

        public msg: NzMessageService,
        public userServie: UserService,
        private cnt: Constant,
        private settingsService: SettingsService,
        private titleService: ReuseTabService,
        private titleServ: TitleService
    ) {
        this.titleService.title = "个人设置";
        this.profileForm = fb.group({
            id: [null],
            name: [null, Validators.compose([Validators.required, Validators.maxLength(30)])],
            email: [null, Validators.compose([Validators.maxLength(50)])],
            tel: [null, Validators.compose([Validators.maxLength(16)])],
            mobile: [null, Validators.compose([Validators.maxLength(16)])],
            sex: [null]
        });
    }

    get name() { return this.profileForm.get('name'); }

    /**
     * 更新信息
     * @param event
     * @param value
     */
    profileSave(event, value) {
        // 只有name是必输的, 所以只校验该字段
        this.profileForm.controls[ 'name' ].markAsDirty();
        this.profileForm.controls[ 'name' ].updateValueAndValidity();
        // 校验表单是否完全正确
        if (this.profileForm.invalid) {
            return;
        }
        // 调用接口修改信息
        let user: User = new User();
        user.id = this.profileForm.get('id').value;
        user.userId = this.settingsService.user.id;
        user.name = this.profileForm.get('name').value;
        user.email = this.profileForm.get('email').value;
        user.mobile = this.profileForm.get('mobile').value;
        user.tel = this.profileForm.get('tel').value;
        this.userServie.modify(user).subscribe(data => {
            this.settingsService.user.name = user.name;
            this.msg.success('Update successful');
        }, (err) => {
            this.msg.error(err.error.message);
        })
    }

    /**
     * 保存密码
     */
    pwdSave() {
        if (!this.pwd.old_password) {
            return this.msg.warning('请输入旧密码');
        }
        if (!this.pwd.new_password) {
            return this.msg.warning('请输入新密码');
        }
        if (!this.pwd.confirm_new_password) {
            return this.msg.warning('请再次输入新密码');
        }
        if (this.pwd.new_password != this.pwd.confirm_new_password) {
            return this.msg.warning('新密码两次输入不一致');
        }

        this.userServie.modifyPassword(this.settingsService.user.username,
            this.pwd.old_password, this.pwd.new_password).pipe(
                catchError(err => {
                    return of(err);
                })
            ).subscribe(data => {
                if (data.ok === true) {
                    this.msg.success('密码修改成功');
                  setTimeout(() => {
                    this.router.navigate(['/passport/login']);
                  }, 500);
                } else {
                    this.msg.error(data.respMsg);
                }
            })
    }

    beforeUpload = (file: File) => {
        const isJPG = file.type === 'image/jpeg';
        const isPNG = file.type === 'image/png';
        if (!isJPG && !isPNG) {
            this.msg.warning(`No support: ${file.type}`);
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            this.msg.warning('The pic file not more than 2MB!');
        }
        return (isJPG || isPNG) && isLt2M;
    }

    private getBase64(img: File, callback: (img: any) => void) {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result));
        reader.readAsDataURL(img);
    }

    handleChange(info: { file: UploadFile }) {
        if (info.file.status === 'uploading') {
            this.loading = true;
            return;
        }
        if (info.file.status === 'done') {
            this.getBase64(info.file.originFileObj, (img: any) => {
                this.loading = false;
                this.avatarUrl = img;
            });
        }
        if (info.file.status === 'error') {
            this.msg.error(info.file.error.error);
        }
    }
    canEdit = true;
  ngOnInit() {}
    // ngOnInit() {
        // this.titleServ.setTitle("Profile")
        // this.uploadUrl = this.userServie.uploadUrl();
        // this.avatarParam.userId = this.settingsService.user.id;
        // this.userServie.info2(this.settingsService.user.id).subscribe(ret => {
        //     if (ret['status'] === 200) {
        //         const data: { [proname: string]: any } = ret['data'];
        //         if (data.attr1) {
        //             this.avatarUrl = `${this.cnt.baseUrl}/api/file/avatar/${data.attr1}`;
        //         } else {
        //             this.avatarUrl = this.settingsService.user.avatar;
        //         }
        //         if (data.app) {
        //             this.canEdit = false;
        //         }
        //         this.profileForm.patchValue({
        //             id: data.id,
        //             name: data.name,
        //             email: data.email,
        //             tel: data.telPhone || data.tel,
        //             mobile: data.mobilePhone || data.mobile
        //         });
        //     } else {
        //         this.msg.error(ret['message']);
        //     }
        // });
    // }
}
